<?php

namespace app\data\controller\control;
use app\data\model\ControlClaimListModel;
use app\data\model\ControlClaimModel;
use app\data\model\StorehouseDataModel;
use think\admin\Controller;
use think\facade\Db;

/**
 * 领用审核
 * Class Cate
 * @package app\data\controller\shop
 */
class ClaimReview extends Controller
{
    /**
     * 指定数据表
     * @var string
     */
    protected $table = 'SnControlClaim';

    /**
     * 指定权限
     */
    protected $authorize = '';
    /**
     * 领用审核
     * @auth true
     * @menu true
     */
    public function index()
    {
        $this->title = '领用审核管理';

        $admin_user = session('user');
        $this->authorize = $admin_user['authorize'];
        $query = $this->_query($this->table)->equal('status')->like('id,plan_title,admin_name');
        //权限重构
        $where[] = array( 'deleted','=', 0);
        // if($this->authorize == 8){
        //     //物流配送中心
        //     $where[] = array('wuliu_id','=',$admin_user['id']);
        //     $query->where($where)->whereIn('plan_status','8,2,4')->order('id desc')->page();
        // }else
        if($this->authorize == 2){
            //科室
            $where[] = array('keshi_id','=',$admin_user['id']);
            $query->where($where)->whereIn('plan_status','2,4')->order('id desc')->page();
        }elseif($this->authorize == 4){
            //精益化管理部
            // $where[] = array('jingyi_id','=',$admin_user['id']);
            $where[] = array('plan_status','=',4);
            $query->where('deleted',0)->where($where)->whereIn('status',[0,1])->whereIn('jingyi_id',[$admin_user['id'],0])->order('id desc')->page();
        }elseif($admin_user['id'] == 10000 || $this->authorize == 7){
            $query->order('id desc')->page();
        }
        $this->assign('authorize',$admin_user['authorize']);
    }


    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _index_page_filter(array &$data)
    {

    }

    /**
     * 查看流程
     * @auth true
     */
    public function ca_detail()
    {
        $this->title = '查看流程';
        $where = array(
            'collect_id'=>input('id')
        );
        $plan_list = Db::name('sn_control_claim_time')->where($where)->orderRaw("field(admin_authorize,'8','2','4')")->select();
        $this->assign('shlist',$plan_list);
        $plan_status = ControlClaimModel::where('id',input('id'))->find();
        $this->assign('info',$plan_status);
        $this->fetch();
    }
    /**
     * 表单结果处理
     * @param boolean $result
     */
    protected function _form_result($result)
    {
        if ($result && $this->request->isPost()) {
            $this->success('数据更新成功！');
        }
    }


    /**
     * 详情
     * @auth true
     */
    public function detail()
    {
        $this->title = '详情';
        $data = input('get.');
        $where = array(
            'deleted'=>0,
            'id'=>input('id')
        );
        $info = ControlClaimModel::where($where)->order('id desc')->find();
        $this->assign('info',$info);
        $plan_list = ControlClaimListModel::where('plan_id',$where['id'])->select()->toArray();
        $total = 0;
        if($plan_list){
            foreach ($plan_list as $k=>$v){
                $plan_list[$k]['material_xjprice'] = $v['material_price'] * $v['material_num'];
                $total += $v['material_price'] * $v['material_num'];
            }
        }else{
            $plan_list = [];
        }

        $this->assign('plan_list',$plan_list);
        $this->assign('total',$total);
        $this->fetch();
    }

    /**
     * 审核通过
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function resume()
    {
        $admin_user = session('user');//['authorize']
        $plan_id = input('id');
        //开启事务
        Db::startTrans();
        try{
            $planTime = array('status'=>1,'time'=>date('Y-m-d H:i:s',time()));
            // if($admin_user['authorize'] == 8){
            //     $applyTime = Db::name('sn_control_claim_time')->where(['collect_id'=>$plan_id,'admin_id'=>$admin_user['id']])->update($planTime);
            //     $planInfo['plan_status'] = 2;
            // }else
            if ($admin_user['authorize'] == 2){
                $applyTime = Db::name('sn_control_claim_time')->where(['collect_id'=>$plan_id,'admin_id'=>$admin_user['id']])->update($planTime);
                $planInfo['plan_status'] = 4;
            }elseif ($admin_user['authorize'] == 4){
                $planInfo['status'] = 1;
                $applyPlan = Db::name('sn_control_claim_list')->where(['plan_id'=>$plan_id])->update(['status'=>1]);
                if (!is_int($applyPlan)) {throw new \Exception("服务器错误");}
                // 子表数据修改
                $applyTime = Db::name('sn_control_claim_time')->where(['collect_id'=>$plan_id,'admin_authorize'=>4])->update($planTime);
            }
            if (!is_int($applyTime)) {throw new \Exception("服务器错误");}
            $resut = ControlClaimModel::where('id',$plan_id)->update($planInfo);
            // 判断是否修改成功
            if (!is_int($resut)) {throw new \Exception("服务器错误");}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());
        }
        $this->success('数据更新成功');
    }

    /**
     * 审核拒绝
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function refusal()
    {
        $adminUser = session('user');
        $plan_id = input('id');
        $refusal_cause = input('refusal_cause');
        $dateTime = date('Y-m-d H:i:s',time());
        $planTime = array('status'=>-1,'time'=>$dateTime,'to_reason'=>$refusal_cause);
        //开启事务
        Db::startTrans();
        try{
            $resut = Db::name('sn_control_claim_time')->where(['collect_id'=>$plan_id,'admin_id'=>$adminUser['id']])->update($planTime);
            if (!is_int($resut)) {$this->error('服务器错误');}
            
            $resut = Db::name('sn_control_claim_list')->where(['plan_id'=>$plan_id])->update(['status'=>-1]);
            if (!is_int($resut)) {$this->error('服务器错误');}
            //退还库存
            $claim = ControlClaimModel::where('id',$plan_id)->find()->toArray();
            $list = ControlClaimListModel::where('plan_id',$claim['id'])->select()->toArray();
            foreach ($list as &$v){
                //库存数量添加
                if(!Db::name('sn_enter_storehouse_'.$claim['admin_id'])->where('material_code',$v['material_code'])->inc('material_num',$v['material_num'])->update()) throw new \Exception("服务器错误");
            }
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());die;
        }
        $this->_save($this->table, ['status' => '-1','reason_name'=>$adminUser['username'],'reason_id'=>$adminUser['id'],'to_reason'=>$refusal_cause,'reason_time'=>$dateTime]);
    }

    /**
     * 批量通过
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function batch_pass()
    {
        $data = input('post.');
        $idArr = explode(',',$data['id']);
        //开启事务
        Db::startTrans();
        try{
            $admin_user = session('user');
            // if($admin_user['authorize'] == 8){
            //     $planInfo['plan_status'] = 2;
            // }else
            if ($admin_user['authorize'] == 2){
                $planInfo['plan_status'] = 4;
            }elseif ($admin_user['authorize'] == 4){
                $planInfo['status'] = 1;
            }
            $resut = ControlClaimModel::whereIn('id',$idArr)->update($planInfo);
            // 判断是否修改成功
            if (!is_int($resut)) {throw new \Exception("服务器错误");}
            // 子表数据修改
            $applyPlan = Db::name('sn_control_claim_list')->whereIn('plan_id',$idArr)->update(['status'=>1]);
            if (!$applyPlan) {throw new \Exception("服务器错误");}
            //流程表数据修改
            $planTime = array('status'=>1,'time'=>date('Y-m-d H:i:s',time()));
            $applyTime = Db::name('sn_control_claim_time')->where('admin_id',$admin_user['id'])->whereIn('collect_id',$idArr)->update($planTime);
            if (!$applyTime) {throw new \Exception("服务器错误");}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());
        }
        $this->success('数据更新成功');
    }


    /**
     * 日志列表
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function detail_log()
    {
        $this->title = '日志列表';
        $data = input('get.');
        $where = array('key'=>$data['id']);
        $info = Db::name('sn_control_claim_log')->where($where)->order('id desc')->select();
        $this->assign('plan_list',$info);
        $this->fetch();
    }

    /*
    * 数量/备注  日志添加
    */
    public function remarks(){
        $index = input('index');
        $id = input('id');
        $remarks = input('remarks');
        $number = input('numbers');
        $info = ControlClaimListModel::where('id',$index)->find();
        if($number>=0 && $number != ''){
            if($info['material_num'] < $number){return json(['code'=>400,'msg'=>'数量过大']);}
            //开启事务
            Db::startTrans();
            try{
                //个人库存数量添加
                
                if(!StorehouseDataModel::where('material_code',$info['material_code'])->inc('material_num',$info['material_num']-$number)->update()) throw new \Exception("服务器错误");
                $saveAll = array(
                    'material_num'=>$number,
                    'material_xjprice'=>round($number * $info['material_price'],2),
                );
                $saveinfo = ControlClaimListModel::where('id',$index)->update($saveAll);
                if($saveinfo === false){return json(['code'=>500,'msg'=>'服务器繁忙']);}
                $admin_user = session('user');
                //添加日志
                $insetAll = array(
                    'plan_id'=>$id,
                    'remarks'=>$remarks,
                    'key'=>$index,
                    'original_num'=>$info['material_num'],
                    'save_num'=>empty($number)?$info['material_num']:$number,
                    'admin_id'=>$admin_user['id'],
                    'admin_name'=>$admin_user['username'],
                    'time'=>date('Y-m-d H:i:s',time())
                );
                $logId = Db::name('sn_control_claim_log')->insertGetId($insetAll);
                if(!$logId){return json(['code'=>500,'msg'=>'服务器繁忙']);}
                Db::commit();
            }catch(\Exception $e){
                // 回滚事务
                Db::rollback();
                // 获取提示信息
                $this->error($e->getMessage());die;
            }
            return json(['code'=>200,'msg'=>'数据已更新']);
        }
    }


}